import React from 'react'
import { Route, Redirect, withRouter } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import PropTypes from 'prop-types'
import TopicList from '../views/topicList'
import Login from '../views/user/login'
import Info from '../views/user/info'

const PrivateRoute = ({ isLogin, component: Component, ...rest }) => (
  <Route
    {...rest}
    render={
      (props) => (
        isLogin
          ? <Component { ...props } />
          : (
            <Redirect
              to={{
                pathname: '/user/login',
              }}
            />
          )
      )
    }
  />
)

PrivateRoute.propTypes = {
  isLogin: PropTypes.bool,
  component: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
}

PrivateRoute.defaultProps = {
  isLogin: false,
}

const InjectedPrivateRoute = withRouter(inject(({ appState }) => {
  return {
    isLogin: appState.user.isLogin,
  }
})(observer(PrivateRoute)))

export default () => [
  <Route exact path="/" render={() => <Redirect to="/index" />} key="/" />,
  <Route exact path="/index" component={TopicList} key="index" />,
  <Route exact path="/user/login" component={Login} key="login" />,
  <InjectedPrivateRoute path="/user/info" component={Info} key="info" />,
]
